package com.mxd.flink.connector.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Lua脚本指令
 * @author rongdi
 * @date 2022/9/20 21:51
 */
public class LuaCmd {

    /**
     * 用来存放jedis scriptLoad lua脚本之后返回的sha字符串
     */
    public static Map<String,String> LUA_SHA_MAP = new ConcurrentHashMap<>();

    /**
     * 实现批量的RPOP的lua脚本存放在本地缓存的key
     */
    public final static String BATCH_RPOP = "BATCH_RPOP";

    /**
     * 实现批量的LPOP的lua脚本存放在本地缓存的key
     */
    public final static String BATCH_LPOP = "BATCH_LPOP";

    /**
     * 实现批量的RPOP，传入key和一次pop的条数
     */
    public final static String BATCH_RPOP_LUA = "local len = redis.call('llen',KEYS[1]);\n" +
            "local datas = {};\n" +
            "if len == 0 then\n" +
            "  return datas;\n" +
            "elseif len > tonumber(ARGV[1]) then \n" +
            " for i=1,tonumber(ARGV[1]) do\n" +
            "  datas[i] = redis.call('rpop',KEYS[1]);\n" +
            " end \n" +
            " return datas; \n" +
            "else \n" +
            " for i=1,len do\n" +
            "  datas[i] = redis.call('rpop',KEYS[1]);\n" +
            " end \n" +
            " return datas; \n" +
            "end";

    /**
     * 实现批量的LPOP，传入key和一次pop的条数
     */
    public final static String BATCH_LPOP_LUA = "local len = redis.call('llen',KEYS[1]);\n" +
            "local datas = {};\n" +
            "if len == 0 then\n" +
            "  return datas;\n" +
            "elseif len > tonumber(ARGV[1]) then \n" +
            " for i=1,tonumber(ARGV[1]) do\n" +
            "  datas[i] = redis.call('lpop',KEYS[1]);\n" +
            " end \n" +
            " return datas; \n" +
            "else \n" +
            " for i=1,len do\n" +
            "  datas[i] = redis.call('lpop',KEYS[1]);\n" +
            " end \n" +
            " return datas; \n" +
            "end";

    /**
     * 根据命令存放lua加载到redis返回的sha字符串
     * @param key
     * @param sha
     * @return
     */
    public static String put(String key,String sha) {
        return LUA_SHA_MAP.put(key,sha);
    }

    /**
     * 根据命令的key获取lua脚本表示的sha字符串
     * @param key
     * @return
     */
    public static String get(String key) {
        return LUA_SHA_MAP.get(key);
    }

}
